package com.xlink.action;

import com.xlink.dto.Device;
import com.xlink.repository.DeviceRepository;
import com.xlink.service.DeviceService;
import org.moon.base.action.BaseAction;
import org.moon.message.WebResponse;
import org.moon.rbac.domain.annotation.MenuMapping;
import org.moon.rest.annotation.Delete;
import org.moon.rest.annotation.Get;
import org.moon.rest.annotation.Post;
import org.moon.rest.annotation.Put;
import org.moon.utils.ParamUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by asus1 on 2015/12/6.
 */
@Controller("deviceAction")//控制器标示
@RequestMapping("/device")//映射路径转发,对于该类中的所有方法，访问时必须有/device前缀
public class DeviceAction extends BaseAction {   //* 控制器，继承至`BaseAction`(`BaseAction`提供领域增强方式的便捷式调用)
    @Resource
    private DeviceService deviceService;

    @Get//表示当前台请求/device时
    @MenuMapping(code = "device", name = "设备信息", parentCode = "test", url = "/device")
    public ModelAndView showPage() {
        return new ModelAndView("pages/xlink/divice");
    }
    //书写相关的业务逻辑方法,将领域模型相关的行为转发给领域处理，将服务类相关的逻辑转发给服务类处理
    @Get("/list")   //查询
    @ResponseBody //这个注解是说返回一个json数据
    public  WebResponse list(HttpServletRequest request){
        //获取参数
        Map<String,Object> params = ParamUtils.getAllParamMapFromRequest(request);
        //把参数传递到servcie层，在service层做实现。
        return WebResponse.build().setResult(deviceService.listForPage(DeviceRepository.class,"list",params));
    }

    @Get("/{deviceId}")   //查看单个设备
    @ResponseBody
    public WebResponse get(@PathVariable("deviceId") Long deviceId){return WebResponse.success(deviceService.get(deviceId));}

    @Post   //添加
    @ResponseBody
    public WebResponse add(HttpServletRequest request,
                           @RequestParam("title")String title,
                           @RequestParam("tags")String tags,
                           @RequestParam("about")String about,
                           @RequestParam("local")String local,
                           @RequestParam("site_flag")int site_flag){
        Device device = new Device();
        device.settitle(title);
        device.setTags(tags);
        device.setabout(about);
        device.setLocal(local);
        device.setsite_flag(site_flag);
        return WebResponse.success(deviceService.add(device));}

    @Put("/{deviceId}")   //修改
    @ResponseBody
    public WebResponse update(@PathVariable("deviceId")Long deviceId, @RequestBody Map<String,Object> params) {
        params.put("deviceId",deviceId);
        deviceService.update(params);
        return WebResponse.success();
    }

    @Delete("/{deviceId}")
    @ResponseBody
    public WebResponse delete(@PathVariable("deviceId")Long deviceId) {
        return WebResponse.build().setResult(deviceService.delete(deviceId));
    }

}
